import { createStore } from "vuex";
import createPersistedState from "vuex-persistedstate";

// 实例化一个store
export default createStore({
  plugins: [createPersistedState()],
  state() {
    return {
      user: {},
      cart_total: 0,
    };
  },
  getters: {
    getUserInfo(state) {
      let now = parseInt((new Date() - 0) / 1000);
      if (state.user.exp === undefined) {
        // 未登录
        state.user = {};
        localStorage.token = "";
        sessionStorage.token = "";
        return null;
      }
      if (state.user.exp < now) {
        // 登录过期
        state.user = {};
        localStorage.token = null;
        sessionStorage.token = null;
        return null;
      }
      return state.user;
    },
  },
  mutations: {
    // 登录
    login(state, payload) {
      state.user = payload;
    },
    // 注销
    logout(state) {
      state.user = {};
      localStorage.token = null;
      sessionStorage.token = null;
    },
    set_cart_total(state, total) {
      // 设置商品数量的总数
      state.cart_total = total;
    },
  },
});
